StartPage.Reader=(function(){return{
	label: null, httpRequest: null, timerTimeout: null, interval: null
	,init: function(){
		this.httpRequest = Cc["@mozilla.org/xmlextras/xmlhttprequest;1"].createInstance(Ci.nsIXMLHttpRequest);
		this.timerTimeout = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
		var self=this
		if (!this.interval) this.interval=setInterval(function(){ self.check.call(self) }, 30000);
		this.updateLabel();
	}
	,updateLabel: function(txt){
		if (txt || txt===0) this.label=txt;
		if (typeof this.label=='undefined' || this.label==null){ this.check(); return; }
		var label=$('#startpage-apps a.reader span.counter', gBrowser.contentDocument);
		label.removeClass('error loading');
		if (this.label=='loading'){ label.addClass('loading'); label.attr('title','Checking...'); }
		else if(this.label=='error'){ label.addClass('error'); label.attr('title','Server error. Try loging in'); }
		else { label.attr('title','You have '+this.label+' unread items'); label.text(this.label); }
	}
	,check: function(){
		var self=this
		this.updateLabel('loading');
		this.httpRequest.open('GET', 'https://www.google.com/reader/api/0/unread-count?all=true&output=json', true);
		this.httpRequest.onload = function(){ self.reqSuccess.call(self); }
		this.httpRequest.onerror = function(){ self.reqError.call(self); }
		this.httpRequest.send(null);
		var event = { notify: function(timer){ self.reqError.call(self) } }
		this.timerTimeout.initWithCallback(event,10000, Ci.nsITimer.TYPE_ONE_SHOT);
	}
	,reqSuccess: function(){
		this.timerTimeout.cancel();
		var resp=JSON.parse(this.httpRequest.responseText);
		var unreads=resp.unreadcounts, i=0, unLen=unreads.length, unreadCount=0;
		for(;i<unLen;i++) if (unreads[i].id.indexOf('/state/com.google/reading-list')!=-1){ unreadCount = unreads[i].count; break; }
		this.updateLabel(unreadCount);
	}	
	,reqError: function(){ this.timerTimeout.cancel(); this.updateLabel('error'); }
}}());
